package com.example.context;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 用户上下文拦截器
 * 从请求头中提取用户信息并设置到ThreadLocal中
 * 只在Spring MVC环境下生效
 */
@Slf4j
@Component
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnClass(HandlerInterceptor.class)
public class UserContextInterceptor implements HandlerInterceptor {

    /**
     * 请求处理前，从请求头中提取用户信息并设置到ThreadLocal
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取用户信息
        String userIdStr = request.getHeader("X-User-Id");
        String username = request.getHeader("X-Username");
        
        // 如果请求头中有用户信息，则设置到ThreadLocal中
        if (StrUtil.isNotBlank(userIdStr) && StrUtil.isNotBlank(username)) {
            try {
                Long userId = Long.parseLong(userIdStr);
                UserContextHolder.setUser(userId, username);
                log.debug("设置用户上下文: userId={}, username={}", userId, username);
            } catch (NumberFormatException e) {
                log.warn("用户ID格式错误: {}", userIdStr);
            }
        }
        
        return true;
    }

    /**
     * 请求处理完成后，清理ThreadLocal中的用户信息
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理用户上下文，避免内存泄漏
        UserContextHolder.clearContext();
        log.debug("清除用户上下文");
    }
}
